import React, { PureComponent } from 'react'
import PropTypes from "prop-types"
import { Form, Input, Tree } from "antd"
import menuList from '@/config/menuConfig'
/**
 * 添加分类的form组件
 */
const Item = Form.Item;
function transformLabelsToTitles(menus) {
    return menus.map(item => {
        const newItem = {
            title: item.label,
            key: item.key,
            icon: item.icon
        };
        if (item.children && item.children.length > 0) {
            newItem.children = transformLabelsToTitles(item.children); // Recursively transform children
        }
        return newItem;
    })
}

export default class AuthForm extends PureComponent {
    constructor(props) {
        super(props);
        //根据传入的角色的menus生成初始状态
        const { menus } = this.props.role
        this.state = {
            treeData: transformLabelsToTitles(menuList),
            checkedKeys: menus
        }
    }

    static propTypes = {
        role: PropTypes.object
    }

    //根据新传入的role来更新checkedKeys状态  会更下面的setState出现冲突
    // static getDerivedStateFromProps(props, state) {
    //     if (props.role !== state.role) {
    //         return {
    //             checkedKeys: props.role.menus
    //         }
    //     }
    //     return null
    // }

    //放在componentDidUpdate里面及时的更新props的值,但是存在问题
    // componentDidUpdate(prevProps) {
    //     if (this.props.role !== prevProps.role) {
    //       this.setState({ checkedKeys: this.props.role.menus });
    //     }else{
    //         return null
    //     }
    //   }

    componentWillReceiveProps(nextProps) {
        const menus = nextProps.role.menus
        this.setState({
            checkedKeys: menus
        })
    }

    //选中某个node时
    onCheck = (checkedKeys) => {

        this.setState({ checkedKeys })
    };

    //为父组件提交获取最新的menus数据方法
    getMenus = () => this.state.checkedKeys;

    render() {
        const { role } = this.props
        const { treeData, checkedKeys } = this.state
        return (
            <div style={{ marginTop: 20 }}>
                <Item label="角色名称" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} >
                    <Input value={role.name} placeholder='请输入角色的名称' disabled></Input>
                </Item>

                <Tree
                    checkable
                    defaultExpandAll={true}
                    treeData={treeData}
                    checkedKeys={checkedKeys}
                    onCheck={this.onCheck}
                />
            </div>
        )
    }
}


